// import { invoke } from '@tauri-apps/api/core';
import { useState } from 'react';
import { open } from '@tauri-apps/plugin-dialog';
import { mkdir, exists } from '@tauri-apps/plugin-fs';
import { Command } from '@tauri-apps/plugin-shell';
import { Button, message, Slider } from 'antd';
import { Header } from '@/components';
import { getFileDir, getFileName } from '@/utils';

export default function Avifenc() {
  const [totalTime, setTotalTime] = useState(0);
  const [quality, setQuality] = useState(80);
  const [loading, setLoading] = useState(false);

  async function encodeFile() {
    try {
      setTotalTime(0);
      setLoading(true);
      // invoke('open_file', { invokeMessage: 'Hello!' });
      const files: any[] | null = await open({
        multiple: true,
        directory: false,
      });

      if (!files || files.length == 0) return;
      const start = Date.now();
      const fileDir = getFileDir(files[0]);
      const isExists = await exists(`${fileDir}/result`);

      if (!isExists) await mkdir(`${fileDir}/result`);
      let hasErr = false,
        msg = '';
      await Promise.all(
        files.map(async (item) => {
          const fileName = getFileName(item);
          const command = Command.sidecar('binaries/avifenc', [
            '-q',
            quality.toString(),
            item,
            `${fileDir}/result/${fileName?.split('.')[0]}.avif`,
          ]);
          const output = await command.execute();
          if (output?.code !== 0) {
            hasErr = true;
            msg = output.stderr;
          }
        }),
      );
      if (hasErr) await message.error({ content: msg });
      setTotalTime(Date.now() - start);
    } catch (e: any) {
      message.error(e.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="relative h-full w-full px-4 py-4">
      <Header title="avif编码" />
      <div className="mt-8 text-[16px] font-bold">质量：{quality}</div>
      <Slider className="mt-4 w-[200px]" value={quality} onChange={(value) => setQuality(value)} min={0} max={100} />

      <div className="mt-8 flex border-collapse flex-row items-center gap-5 rounded-lg border px-4 py-4">
        <div className="text-[16px] font-bold">耗时：{totalTime}ms</div>

        <Button className="h-[40px] w-[150px] border" loading={loading} onClick={encodeFile}>
          选择文件
        </Button>
      </div>
    </div>
  );
}
